package com.qinglei.recoup.system.controller;


import com.qinglei.recoup.common.domain.CommonRes;

import com.qinglei.recoup.system.domain.UserWechat;
import com.qinglei.recoup.system.domain.UserWechatComment;
import com.qinglei.recoup.system.service.UserWechatService;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author dqh
 */
@RestController
@RequestMapping("/user-wechat")
public class UserWechatController {

    @Autowired
    private UserWechatService userWechatService;

    @Value("${wx.appId}")
    private String appId;

    @Value("${wx.appSecret}")
    private String appSecret;

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("/add")
    public CommonRes add(@Valid @RequestBody  UserWechat userWechat){
      return  userWechatService.add(userWechat);
    }

    @GetMapping("/getByOpenId")
    public CommonRes getByOpenId(String openId){
        if(StringUtils.isEmpty(openId)){
            return CommonRes.failed()
                    .setMsg("暂未登录");
        }
        UserWechat userWechat = userWechatService.getByOpenId(openId);
        return  CommonRes.ok(userWechat).setMsg("成功！");
    }

    @PostMapping("/comment")
    public CommonRes comment(@Valid @RequestBody UserWechatComment userWechatComment){

        return  userWechatService.comment(userWechatComment);

    }

    @PostMapping("/isComment")
    public CommonRes isComment(@Valid @RequestBody UserWechatComment userWechatComment){

        return  userWechatService.isComment(userWechatComment);

    }

    @GetMapping("/getWxData")
    public CommonRes getWxData(String code,String state){
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appId+"&secret="
                +appSecret+"&code="+code+"&grant_type=authorization_code";
        try {
            String body2 = restTemplate.getForObject(url,String.class);
            JSONObject jsonObject = new JSONObject(body2);
            String result = jsonObject.toString();
            if(result.contains("7200")){
                return CommonRes.ok().setData(result).setMsg("获取成功");
            }else{
                return CommonRes.failed().setMsg("获取失败");
            }

        }catch (Exception e){
            e.printStackTrace();
            return CommonRes.failed();
        }

    }
}
